def check_multiple_jpegs(file_path):
    """检查文件中是否包含多个JPG图片(通过查找多个结束标记)"""
    with open(file_path, 'rb') as f:
        data = f.read()
    
    # JPG结束标记
    jpg_end_marker = b'\xff\xd9'
    
    # 查找所有结束标记位置
    end_positions = [i for i in range(len(data)-1) if data[i:i+2] == jpg_end_marker]
    
    if len(end_positions) > 1:
        print(f"发现{len(end_positions)}个JPG结束标记，可能包含多个图片")
        print(f"结束标记位置: {end_positions}")
        return True
    return False

from PIL import Image
import io

def check_thumbnail(img_path):
    """检查JPG文件中的缩略图"""
    try:
        with Image.open(img_path) as img:
            # 检查是否有缩略图
            if hasattr(img, 'thumbnail'):
                print("发现缩略图")
                return True
            
            # 另一种检查缩略图的方法
            img_data = img.tobytes()
            thumb_pos = img_data.find(b'\xff\xd8\xff')  # 查找可能的缩略图开始
            if thumb_pos > 0:
                print(f"发现可能的缩略图(位置: {thumb_pos})")
                return True
        return False
    except Exception as e:
        print(f"图片读取错误: {e}")
        return False
    
from PIL import Image
from PIL.ExifTags import TAGS

def check_exif_thumbnail(img_path):
    """检查EXIF数据中的缩略图"""
    try:
        with Image.open(img_path) as img:
            exif_data = img._getexif()
            if exif_data:
                for tag_id, value in exif_data.items():
                    tag_name = TAGS.get(tag_id, tag_id)
                    if tag_name == 'Thumbnail' or tag_name == 513:  # 513是缩略图偏移量
                        print("EXIF中发现缩略图数据")
                        return True
        return False
    except Exception as e:
        print(f"EXIF读取错误: {e}")
        return False
    
def detect_multiple_images(file_path):
    """综合检测JPG中是否包含多个图片"""
    print(f"分析文件: {file_path}")
    
    results = {
        'multiple_markers': check_multiple_jpegs(file_path),
        'thumbnail': check_thumbnail(file_path),
        'exif_thumbnail': check_exif_thumbnail(file_path),  
    }
    
    if any(results.values()):
        print("\n结论: 此文件可能包含多个图片")
        return True
    
    print("\n结论: 未检测到多个图片")
    return False

from PIL import Image
import io

def extract_images_by_markers(file_path, output_prefix="extracted"):
    """通过识别多个JPG结束标记来提取图片"""
    with open(file_path, 'rb') as f:
        data = f.read()
    
    # JPG开始和结束标记
    start_marker = b'\xff\xd8\xff'
    end_marker = b'\xff\xd9'
    
    # 查找所有图片位置
    start_poses = []
    end_poses = []
    images = []
    pos = 0
    while True:
        start_pos = data.find(start_marker, pos)
        if start_pos == -1:
            break
        
        end_pos = data.find(end_marker, start_pos)
        if end_pos == -1:
            break
        start_poses.append(start_pos)
        end_poses.append(end_pos)
        pos = end_pos + 2
    
    for start_pos in start_poses:
        for end_pos in end_poses:
            # 包含结束标记的完整图片数据
            image_data = data[start_pos:end_pos+2]
            images.append(image_data)
    
    # 保存提取的图片
    for i, img_data in enumerate(images):
        try:
            img = Image.open(io.BytesIO(img_data))
            output_path = f"{output_prefix}_{i}.jpg"
            img.save(output_path)
            print(f"成功保存图片: {output_path}")
        except Exception as e:
            print(f"无法解析图片{i}: {e}")
    
    return len(images)

file = 'test-data/file_tu.jpg'

# 使用示例
# extracted_count = extract_images_by_markers(file)
# print(f"共提取出{extracted_count}张图片")
detect_multiple_images(file)

import os
from PIL import Image
import io

def extract_jpegs(file_path, output_dir="extracted"):
    """改进版 JPG 提取，更接近 foremost 的算法"""
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    with open(file_path, 'rb') as f:
        data = f.read()

    start_marker = b'\xff\xd8'  # JPG 开始
    end_marker = b'\xff\xd9'    # JPG 结束

    pos = 0
    extracted = 0

    while pos < len(data) - 1:
        # 查找 JPG 开始标记
        start = data.find(start_marker, pos)
        if start == -1:
            break

        # 查找 JPG 结束标记（从 start 开始找）
        end = data.find(end_marker, start)
        if end == -1:
            break  # 如果没有结束标记，跳过

        # 提取 JPG 数据（包含结束标记）
        jpg_data = data[start:end + 2]

        # 尝试用 Pillow 打开，验证是否有效
        try:
            img = Image.open(io.BytesIO(jpg_data))
            img.verify()  # 验证图片完整性
            output_path = os.path.join(output_dir, f"extracted_{extracted}.jpg")
            with open(output_path, 'wb') as out_f:
                out_f.write(jpg_data)
            extracted += 1
            print(f"成功提取图片: {output_path} (大小: {len(jpg_data)} 字节)")
            pos = end + 2  # 继续搜索下一张图片
        except:
            pos += 2  # 如果无效，跳过 2 字节继续搜索

    print(f"共提取 {extracted} 张图片")

# 使用示例
# extract_jpegs(file)